package com.winz.cultureapp.widge;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.AdapterView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX;
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage;
import com.tencent.mm.opensdk.modelmsg.WXWebpageObject;
import com.winz.cultureapp.R;
import com.winz.cultureapp.application.DemoApplication;
import com.winz.cultureapp.utils.BitMapUtils;
import com.winz.cultureapp.utils.Logger;

import java.io.ByteArrayOutputStream;
import java.util.HashMap;

import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;

/**
 * 分享
 */
public class ShareSomething implements PlatformActionListener {
    private ShareDialog shareDialog;
    private Context context;

    /**
     * 复制到剪切板
     *
     * @param savedInstanceState
     */
    private String clipboard;

    public ShareSomething(Context context) {
        this.context = context;

    }

    public void forShare(String title, String text, String url, String imageUrl) {

        shareDialog = new ShareDialog(context);
        shareDialog.setCancelButtonOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                shareDialog.dismiss();

            }
        });
        shareDialog.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1,
                                    int arg2, long arg3) {
                HashMap<String, Object> item = (HashMap<String, Object>) arg0.getItemAtPosition(arg2);
                if (item.get("ItemText").equals("微信") || item.get("ItemText").equals("朋友圈")) {
                    Logger.d("微信");
                    //初始化一个WXWebpageObject，填写url
                    WXWebpageObject webpage = new WXWebpageObject();
                    webpage.webpageUrl = url;

                    //用 WXWebpageObject 对象初始化一个 WXMediaMessage 对象
                    WXMediaMessage msg = new WXMediaMessage(webpage);
                    msg.title = title;
                    msg.description = text;
                    Glide.with(context)
                            .load(imageUrl)
                            .asBitmap()
                            .into(new SimpleTarget<Bitmap>(100, 100) {
                                @Override
                                public void onResourceReady(Bitmap thumbBmp, GlideAnimation<? super Bitmap> glideAnimation) {
                                    // 下载成功回调函数
                                    msg.thumbData = bmpToByteArray(BitMapUtils.compressImage(thumbBmp, 32));
                                    //构造一个Req
                                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                                    req.transaction = buildTransaction("webpage");
                                    req.message = msg;
                                    req.scene = item.get("ItemText").equals("微信")?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;

                                    //调用api接口，发送数据到微信
                                    DemoApplication.api.sendReq(req);
                                }

                                @Override
                                public void onLoadFailed(Exception e, Drawable errorDrawable) {
                                    // 下载失败回调
                                    Bitmap thumbBmp = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_logo);

                                    msg.thumbData = bmpToByteArray(BitMapUtils.compressImage(thumbBmp, 32));
                                    //构造一个Req
                                    SendMessageToWX.Req req = new SendMessageToWX.Req();
                                    req.transaction = buildTransaction("webpage");
                                    req.message = msg;
                                    req.scene = item.get("ItemText").equals("微信")?SendMessageToWX.Req.WXSceneSession:SendMessageToWX.Req.WXSceneTimeline;

                                    //调用api接口，发送数据到微信
                                    DemoApplication.api.sendReq(req);
                                }
                            });
                } else if (item.get("ItemText").equals("QQ")) {
                    Logger.d("QQ");

                } else if (item.get("ItemText").equals("QQ空间")) {
                    Logger.d("QQ空间");

                }
                shareDialog.dismiss();

            }
        });
    }

    public byte[] bmpToByteArray(Bitmap bm) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
        return baos.toByteArray();
    }

    private String buildTransaction(final String type) {
        return (type == null) ? String.valueOf(System.currentTimeMillis()) : type + System.currentTimeMillis();
    }


    @Override
    public void onCancel(Platform arg0, int arg1) {//回调的地方是子线程，进行UI操作要用handle处理
        handler.sendEmptyMessage(5);

    }

    @Override
    public void onComplete(Platform arg0, int arg1, HashMap<String, Object> arg2) {//回调的地方是子线程，进行UI操作要用handle处理
        if (arg0.getName().equals("")) {// 判断成功的平台是不是新浪微博
            handler.sendEmptyMessage(1);
        }
// else if (arg0.getName().equals(WechatMoments.NAME)) {
//            handler.sendEmptyMessage(2);
//        } else if (arg0.getName().equals(QQ.NAME)) {
//            handler.sendEmptyMessage(3);
//        } else if (arg0.getName().equals(QZone.NAME)) {
//            handler.sendEmptyMessage(4);
//        }

    }

    @Override
    public void onError(Platform arg0, int arg1, Throwable arg2) {//回调的地方是子线程，进行UI操作要用handle处理
        arg2.printStackTrace();
        Message msg = new Message();
        msg.what = 6;
        msg.obj = arg2.getMessage();
        handler.sendMessage(msg);
    }

    Handler handler = new Handler() {

        @Override
        public void handleMessage(Message msg) {
//            switch (msg.what) {
//                case 1:
//                    Toast.makeText(context.getApplicationContext(), context.getString(R.string.share_succ), Toast.LENGTH_LONG).show();
//                    break;
//                case 5:
//                    Toast.makeText(context.getApplicationContext(), context.getString(R.string.share_cancel), Toast.LENGTH_LONG).show();
//                    break;
//                case 6:
//                    Toast.makeText(context.getApplicationContext(), context.getString(R.string.share_fail) /*+ msg.obj*/, Toast.LENGTH_LONG).show();
//                    break;
//                default:
//                    Toast.makeText(context.getApplicationContext(), context.getString(R.string.share_unknown), Toast.LENGTH_LONG).show();
//                    break;
//            }
        }

    };

    public String getClipboard() {
        return clipboard;
    }
}
